<?php

class REntidadController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(		
			
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('index','view','create','buscarEntidadDeporte','update','admin','delete','autoCompletar','asignarDetalles','eliminar'),
				'users'=>Yii::app()->getModule('user')->getAdmins(),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionBuscarEntidadDeporte()
	{
	
	$entidades = REntidad::model()->findAll(array('order'=>'grid_grupo','condition'=>'grid_deporte_actividad_id=:x', 'params'=>array(':x'=>(int)$_POST['deporte'])));
		
		
											
	$data = CHtml::listData($entidades, 'grid_entidad_id', 'grid_grupo');
	
	echo CHtml::tag('option',
				array('value'=>''),CHtml::encode('ELEGIR'),true);	
	
	foreach ($data as $value=>$name)
		{
			echo CHtml::tag('option',
				array('value'=>$value),CHtml::encode($name),true);				
		}
	
	
	}
	
	public function actionEliminar()
	{
		$DEId = $_POST['DEId'];
  		
  		$connection = Yii::app()->db;
		$command = $connection->createCommand("
		   DELETE FROM grid_r_detalle_entidad WHERE grid_detalle_entidad_id='{$DEId}';");
		$command->query();
		
	}

	public function actionAsignarDetalles($id)
	{
		if(!isset($id))
			$this->redirect('create');
			
		$rEntidad = REntidad::model()->findByPk($id);		
		
		if($rEntidad)
		{
						
			/** QUERY PARA SACAR PARTICIPANTES A REGISTRAR ****/
			$criteria = new CDbCriteria();
			
			$criteria->alias ='gp';											
					
					$criteria->join='INNER JOIN grid_inscripcion_nominal gin ON gin.inscripcion_nominal_persona=gp.persona_id
						INNER JOIN grid_deporte_actividad gda ON gda.deporte_actividad_id = gin.inscripcion_nominal_deporte_actividad
						INNER JOIN grid_users gu ON gu.id = gp.user_id';										
					
					$criteria->order="gp.persona_nacionalidad,gp.persona_nombres_apellidos,gin.inscripcion_nominal_estado";					
					if($rEntidad->grid_genero!="POSTAS")
					{
					$criteria->condition="gin.inscripcion_nominal_estado = 'ACREDITADO' 
						AND gin.inscripcion_nominal_deporte_actividad = ".$rEntidad->grid_deporte_actividad_id."
						AND gp.persona_genero = '".$rEntidad->grid_genero."'
						AND gp.persona_nacionalidad = ".$rEntidad->grid_pais_id;
					}
					else
					{
						$criteria->condition="gin.inscripcion_nominal_estado = 'ACREDITADO' 
						AND gin.inscripcion_nominal_deporte_actividad = ".$rEntidad->grid_deporte_actividad_id."						
						AND gp.persona_nacionalidad = ".$rEntidad->grid_pais_id;
					}
					$dataProvider=new CActiveDataProvider('Persona',					
					array(
						'criteria'=>$criteria,		
						)
					);	
					
					$dataProvider->pagination = false;
			/** FIN QUERY PARA SACAR PARTICIPANTES A REGISTRAR ****/
														
					
			/** QUERY PARA SACAR PARTICIPANTES REGISTRADOS ****/
			
			$criteriaRegistrados = new CDbCriteria();
			$criteriaRegistrados->condition="grid_entidad_id = ". $rEntidad->grid_entidad_id;
			
			$dataProviderRegistrados=new CActiveDataProvider('RDetalleEntidad',					
					array(
						'criteria'=>$criteriaRegistrados,		
						)
					);
			
			/** FIN QUERY PARA SACAR PARTICIPANTES REGISTRADOS ****/

					$dataProviderRegistrados->pagination = false;
		if(isset($_POST['Persona']))
		{			
			//for ($i = 0; $i < $dataProvider->getTotalItemCount(); $i++) {
			$i=0;
			
			foreach ($dataProvider->getData() as $data){
				
				$i++;
				
				if(isset($_POST['Persona'][$i]))
				{
					if(isset($_POST['Persona'][$i]['persona_seleccionada']))
					{		
						$rDetalle= new RDetalleEntidad();
						$rDetalle->grid_entidad_id = $_POST['Persona'][$i]['grid_entidad_id'];
						$rDetalle->grid_persona_id = $_POST['Persona'][$i]['persona_id'];	
						if(!$rDetalle->save())
								$this->redirect('create');		
												
					}					
				}	
			}
		}
					
		$this->render('asignarDetalles',array('dataProvider'=>$dataProvider,'rEntidad'=>$rEntidad,'registrados'=>$dataProviderRegistrados));
		
		}
		else 
			$this->redirect('create');
	}
	
	// This function will echo a JSON object 
	// of this format:
	// [{id:id, name: 'name'}]
	public function actionAutoCompletar(){
	      
		  $personaJSON = array();
	    
	         // test table is for the sake of this example
	         $sql = '
	         SELECT gp.persona_id,gp.persona_nombres_apellidos from grid_persona gp
				INNER JOIN grid_inscripcion_nominal gin ON gin.inscripcion_nominal_persona=gp.persona_id
				INNER JOIN grid_deporte_actividad gda ON gda.deporte_actividad_id = gin.inscripcion_nominal_deporte_actividad
				INNER JOIN grid_users gu ON gu.id = gp.user_id
				WHERE gp.persona_nombres_apellidos like :nombres_apellidos and (gin.inscripcion_nominal_aplica = 15 or  gin.inscripcion_nominal_aplica = 43)';
	         
	         $cmd = Yii::app()->db->createCommand($sql);
	         $cmd->bindValue(":nombres_apellidos","%".strtolower($_GET['term'])."%", PDO::PARAM_STR);
	         $personaJSON = $cmd->queryAll();
	         
	      	 foreach($personaJSON as $persona) {
		  			$personaJSON[] = array(
							'label'=>$persona['persona_nombres_apellidos'],
							'value'=>$persona['persona_nombres_apellidos'],
							'id'=>$persona['persona_id'],
							);
			}		
		
	    
	      
	      echo CJSON::encode($personaJSON);
	      
	      //Yii::app()->end();
	}
	
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new REntidad;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['REntidad']))
		{
			$model->attributes=$_POST['REntidad'];
			$model->user_id= Yii::app()->user->id;
			$model->ip_registro= Yii::app()->request->userHostAddress;
			$model->fecha_registro = date('Y-m-d h:i:s');
			
			if($model->save())
			{
				$this->redirect(array('asignarDetalles','id'=>$model->grid_entidad_id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['REntidad']))
		{
			$model->attributes=$_POST['REntidad'];
			if($model->save())
				$this->redirect(array('asignarDetalles','id'=>$model->grid_entidad_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('REntidad');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new REntidad('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['REntidad']))
			$model->attributes=$_GET['REntidad'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=REntidad::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='rentidad-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
